package com.aletto.general_store.presenters;

import android.content.Context;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aletto.general_store.R;
import com.aletto.general_store.data.DataRepository;
import com.aletto.general_store.data.MockDataSource;
import com.aletto.general_store.data.model.Goods;
import com.aletto.general_store.data.model.PageResponse;
import com.aletto.general_store.presenters.core.SimplePageTemplate;
import com.aletto.general_store.ui.activities.GoodsDetailsActivity;
import com.sisyphus.spinach.core.INetPageTask;
import com.sisyphus.spinach.core.model.IPageResponse;
import com.sisyphus.spinach.core.model.IResponse;
import com.sisyphus.spinach.network.presenters.NetPageTask;
import com.sisyphus.spinach.ui.configs.impl.DefaultPageTemplate;
import com.aletto.general_store.ui.GoodsGridItemDecoration;
import com.aletto.general_store.ui.adapters.GoodsListAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;


import io.reactivex.rxjava3.core.Observable;
import me.jessyan.autosize.utils.AutoSizeUtils;

/**
 * 商品列表
 */
public class GoodsPageTemplate extends SimplePageTemplate<Goods> {

    public GoodsPageTemplate(RecyclerView recyclerView, SmartRefreshLayout refreshLayout) {
        super(recyclerView, refreshLayout);

        // 清除，防止叠加
        int itemDecorationCount = recyclerView.getItemDecorationCount();
        for (int index = 0; index < itemDecorationCount; index++) {
            recyclerView.removeItemDecorationAt(index);
        }

        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        recyclerView.addItemDecoration(new GoodsGridItemDecoration(AutoSizeUtils.dp2px(getContext(), 2)));
    }

    @Override
    public BaseQuickAdapter<Goods, BaseViewHolder> adapter(RecyclerView recyclerView) {
        GoodsListAdapter goodsListAdapter = new GoodsListAdapter();

        // 商品详情
        goodsListAdapter.setOnItemClickListener((adapter, view, position) -> {
            Context context = view.getContext();
            Goods goods = (Goods) adapter.getItem(position);
            context.startActivity(GoodsDetailsActivity.newIntent(context, goods));
        });

        return goodsListAdapter;
    }

    @Override
    public INetPageTask.Presenter<Goods, INetPageTask.View<Goods>> presenter() {
        return new NetPageTask<>() {
            @Override
            public Observable<? extends IResponse<? extends IPageResponse<Goods>>> execute(int page) {
                return DataRepository.getInstance().homeGoods(page, PageResponse.SIZE);
            }
        };
    }

}
